package com.yeshen.pmtea.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.yeshen.pmtea.R;
import com.yeshen.pmtea.adapters.NewsAdapter;
import com.yeshen.pmtea.beans.DBHelper;
import com.yeshen.pmtea.beans.News;
import com.yeshen.pmtea.utils.SqliteUtils;

import java.util.List;

public class CollectActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener {
     private ListView mListView;
    private List<News> newsList;
    private NewsAdapter mAdapter;
    private DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect);
        initView();
    }
    private void initView() {
        newsList= SqliteUtils.getListFromSQL(CollectActivity.this);
        mListView = (ListView) findViewById(R.id.lv_collect);
        Log.d("flag", "---------------initView: " +newsList.size());
        mAdapter = new NewsAdapter(newsList,this);

        mListView.setAdapter(mAdapter);
        //设置点击事件,跳转到具体的页面
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(CollectActivity.this,NewsItemContentActivity.class);
                News news = newsList.get(i);
                intent.putExtra("key",news);

                startActivity(intent);
            }
        });
        //长按删除
        mListView.setOnItemLongClickListener(this);

    }

    public void onBackCollect(View view) {
        finish();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        AlertDialog.Builder builder =new AlertDialog.Builder(this);
        View view1 = LayoutInflater.from(this).inflate(R.layout.dialog_item, null);
        builder.setView(view1);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //newsList.remove(position);
                //删除数据库数据
                dbHelper = new DBHelper(CollectActivity.this);
                SQLiteDatabase db = dbHelper.getReadableDatabase();
                db.delete("collect", "title=?", new String[]{newsList.get(position).getTitle()});
                newsList.remove(position);
                mAdapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消",null);
        builder.create().show();

        return true;
    }
}
